package zuo.algo.c07;

import zuo.algo.data.TreeNode;
import zuo.algo.util.TreeUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 00:02-判断一个树是不是搜索二叉树
 * 搜索二叉树中序遍历是有序数组
 */
public class TestBST {

    public static boolean isBST1(TreeNode head) {
        List<Integer> sortList = new ArrayList<>();
        process(head, sortList);
        for (int i = 1; i < sortList.size(); i++) {
            if (sortList.get(i - 1) > sortList.get(i)) {
                return false;
            }
        }
        return true;
    }

    private static void process(TreeNode head, List<Integer> sortList) {
        if (head == null) {
            return;
        }
        process(head.left, sortList);
        sortList.add(head.val);
        process(head.right, sortList);
    }

    /**
     * 00:45-使用套路求是否是搜索二叉树
     */
    public static boolean isBST2(TreeNode head) {
        if (head == null) {
            return true;
        }
        TreeNode node = head;
        LinkedList<TreeNode> stack = new LinkedList<>();
        int preVal = Integer.MIN_VALUE;
        while (node != null || !stack.isEmpty()) {
            if (node != null) {
                stack.push(node);
                node = node.left;
            } else {
                node = stack.pop();
                if (preVal > node.val) {
                    return false;
                } else {
                    preVal = node.val;
                }
                System.out.println(node.val);
                node = node.right;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        TreeNode head = TreeUtils.getTree();
        boolean bst1 = isBST1(head);
        boolean bst2 = isBST2(head);
        System.out.println(bst1 == bst2);
    }
}
